﻿using System;
using System.IO;

public class ConstUtil
{
    private const string CLIENT_CONFIG_FILE_NAME = "Config/client_config.xml";

    public void Init()
    {
        // 第一步,将client_config.xml拷贝到SD卡.
        // 如果SD卡有此文件,则不会再拷贝.
        CopyClientConfigToPersistentPath();
        // 读取并解析配置.
        ReadClientConfig();
    }

    /// <summary>
    ///     读取并解析配置.
    /// </summary>
    private void ReadClientConfig()
    {
        var context = FileUtil.ReadFileToString(CLIENT_CONFIG_FILE_NAME, EnumFileType.PERSISTENT);
        if (!string.IsNullOrEmpty(context))
        {
            ParseConfig(context);
        }
    }

    /// <summary>
    ///     解析配置.
    /// </summary>
    private void ParseConfig(string context)
    {
        var stringReader = new StringReader(context);
        var configLine = stringReader.ReadLine();
        while (configLine != null)
        {
            if (configLine.Equals(string.Empty) || configLine.StartsWith("<!--"))
            {
                //跳过空行和注释.
                configLine = stringReader.ReadLine();
                continue;
            }

            var splitIndex = configLine.IndexOf('=');
            if (splitIndex < 0)
            {
                LogWrapper.LogError("LoadLoadingConfig Error, configLine:", configLine);
                configLine = stringReader.ReadLine();
                continue;
            }
            LogWrapper.LogDebug(configLine);
            var key = configLine.Substring(0, splitIndex);
            var value = configLine.Substring(splitIndex + 1);
            switch (key)
            {
                case "Test":
                    Consts.m_Test = int.Parse(value);
                    break;
                case "LogLevel":
                    Consts.m_LogLevel = value;
                    break;
                case "Example1_Actor_Count":
                    Consts.EXAMPLE1_ACTOR_COUNT = int.Parse(value);
                    break;
                case "EXAMPLE1_USE_BYTES":
                    Consts.EXAMPLE1_USE_BYTES = bool.Parse(value);
                    break;
                case "EXAMPLE1_USE_CAPACITY":
                    Consts.EXAMPLE1_USE_CAPACITY = bool.Parse(value);
                    break;
            }

            configLine = stringReader.ReadLine();
        }
    }

    /// <summary>
    ///     将client_config.xml移动到持久化目录.目的是为了修改配置方便.
    /// </summary>
    private void CopyClientConfigToPersistentPath()
    {
#if !UNITY_EDITOR
        // 编辑器下强制copy.
        if (FileUtil.CheckFileExist(CLIENT_CONFIG_FILE_NAME, EnumFileType.PERSISTENT))
        {
            LogWrapper.LogDebug("[ConstUtil][CopyClientConfigToPersistentPath] file has exist:",
                CLIENT_CONFIG_FILE_NAME);
            return;
        }
#endif

        FileUtil.CopyFile(CLIENT_CONFIG_FILE_NAME, EnumFileType.STREAMING_ASSETS, CLIENT_CONFIG_FILE_NAME,
            EnumFileType.PERSISTENT);
    }
}